using System;
using System.Collections.Generic;
using System.Reflection;
using Castle.Core.Interceptor;

namespace CosyTrade.Network.Proxy
{
    public class ProxyInterceptor : IInterceptor
    {
        private readonly IMethodInvoke remotingCaller;
        private readonly string addinName;
        
        public ProxyInterceptor(IMethodInvoke remotingCaller, string addinName)
        {
            this.remotingCaller = remotingCaller;
            this.addinName = addinName;
        }

        public void Intercept(IInvocation invocation)
        {
            ParameterInfo[] argsPara = invocation.Method.GetParameters();
            List<Type> argsTypes = new List<Type>();
            foreach (ParameterInfo info in argsPara)
                argsTypes.Add(info.ParameterType);
            Request reqeust = new Request(addinName, invocation.Method.Name, argsTypes.ToArray(), invocation.Arguments);
            Response response =
                (Response) FormatterHelper.BytesToOBject(remotingCaller.Invoke(FormatterHelper.ObjectToBytes(reqeust)));
            if (response.Exception != null) throw response.Exception;
            invocation.ReturnValue = response.ReturnValue;
        }

    }
}